package com.example.origin.finance.service;

import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.example.origin.finance.enums.TableNameEnum;
import com.example.origin.finance.utils.CalcUtil;
import com.example.origin.finance.utils.InheritableThreadLocalUtil;
import com.example.origin.finance.utils.TableUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public abstract class AbstractUtilService {

    @Resource
    protected RestTemplate restTemplate;
    @Resource
    protected MongoTemplate mongoTemplate;

    protected void createIndex(String table) {
        Index index = new Index();
        index.on("code", Sort.Direction.ASC);
        mongoTemplate.indexOps(table).ensureIndex(index);
    }

    protected static void logProcess(int i, int size) {
        BigDecimal decimal = CalcUtil.multiply(CalcUtil.divide(i, size), 100).setScale(2, RoundingMode.HALF_UP);
        log.info("process：{} %", decimal);
    }

    protected String getXueqiuCookie() {
        Object xueqiuCookie = InheritableThreadLocalUtil.get();
        if (xueqiuCookie ==null) {
            xueqiuCookie = RequestContextHolder.currentRequestAttributes().getAttribute("xueqiuCookie", RequestAttributes.SCOPE_REQUEST);
        }
        return Objects.requireNonNull(xueqiuCookie).toString();
    }

    protected static boolean setParamMap(String code, Map<String, String> paramMap) {
        if (code.startsWith("1") || code.startsWith("0") || code.startsWith("3") || code.startsWith("2")) {
            paramMap.put("symbol", "SZ" + code);
            return true;
        }
        if (code.startsWith("5") || code.startsWith("6") || code.startsWith("9")) {
            paramMap.put("symbol", "SH" + code);
            return true;
        }

        if (!Pattern.matches("\\d+",code)){
            paramMap.put("symbol", code);
            return true;
        }
        return false;
    }



}
